/* 
* Copyright (c) 2009, The University of Texas at Austin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, 
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation and/or other materials 
* provided with the distribution.
*
* Neither the name of The University of Texas at Austin nor the names of its contributors may be 
* used to endorse or promote products derived from this software without specific prior written 
* permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Input;
using Bio.Data.Providers;
using Bio.Views.ViewModels;
using BioBrowser.Models;
using JulMar.Windows.Mvvm;
using JulMar.Windows.Interfaces;

namespace BioBrowser.ViewModels
{
    /// <summary>
    /// This class represents the primary View Model which supports the BioBrowser application.
    /// </summary>
    public class MainViewModel : ViewModel
    {
        public ObservableCollection<BioViewModel> DockedViews { get; private set; }
        public ObservableCollection<SelectionViewModel> Categories { get; private set; }

        private BioViewModel _selectedView;
        public BioViewModel SelectedView
        {
            get { return _selectedView; }
            set { _selectedView = value; OnPropertyChanged("SelectedView"); }
        }

        public ICommand NotifyCloseCommand { get; private set; }

        /// <summary>
        /// Constructor
        /// </summary>
        public MainViewModel()
        {
            NotifyCloseCommand = new DelegatingCommand(OnViewClosed);

            // Initialize MEF and add ourselves and the data loaders
            try
            {
                MefManager.Current.ComposeParts(this, Extensions.Current);
            }
            catch (CompositionException ex)
            {
                IErrorVisualizer uiVisualizer = Resolve<IErrorVisualizer>();
                if (uiVisualizer != null)
                    uiVisualizer.Show("Failed to locate required components", ex.Message);
                Environment.Exit(-1);
            }

            if (Extensions.Current.DataProviders == null ||
                Extensions.Current.DataProviders.Count() == 0)
            {
                IErrorVisualizer uiVisualizer = Resolve<IErrorVisualizer>();
                if (uiVisualizer != null)
                    uiVisualizer.Show("Failed to locate required components", "No Data Providers found - make sure all required assemblies are copied into the deployment directory.");
                Environment.Exit(-1);
            }

            // Register with message mediator
            RegisterWithMessageMediator();

            // Setup the docked views + menu handlers
            DockedViews = new ObservableCollection<BioViewModel>();
            Categories = new ObservableCollection<SelectionViewModel> {
                 // Open workspaces
                 new WorkspaceRootViewModel {Header = "Workspaces", Image="images/attachment.png" },
             };

            // Populate sequence loaders
            var loaders = Extensions.Current.DataProviders.Where(bdl => (bdl.SupportedTypes & (BioFormatType.Sequence | BioFormatType.AlignedSequence)) > 0).Select(bdl => bdl);
            if (loaders.Count() > 0)
                Categories.Add(new BioCategoryViewModel { Header = "Sequence Alignments", Image = "images/alignment.ico", FormatLoaders = loaders });

            // Populate structure loaders
            loaders = Extensions.Current.DataProviders.Where(bdl => (bdl.SupportedTypes & (BioFormatType.Structure | BioFormatType.Structure2D)) > 0).Select(bdl => bdl);
            if (loaders.Count() > 0)
                Categories.Add(new BioCategoryViewModel { Header = "Structure Diagrams", Image = "images/secondaryStruct.ico", FormatLoaders = loaders });

            // 3D molecular viewers
            loaders = Extensions.Current.DataProviders.Where(bdl => (bdl.SupportedTypes & (BioFormatType.MoleculeStructure)) > 0).Select(bdl => bdl);
            if (loaders.Count() > 0)
                Categories.Add(new BioCategoryViewModel { Header = "Molecular Structure (3D)",Image = "images/molecule.ico",  FormatLoaders = loaders });
        }

        [MessageMediatorTarget(Bio.Views.ViewModels.ViewMessages.NewDockedView)]
        private void OnAddNewDockedWindow(object parameter)
        {
            BioViewModel vm = (BioViewModel)parameter;
            DockedViews.Add(vm);
            SelectedView = vm;
        }

        [MessageMediatorTarget(Bio.Views.ViewModels.ViewMessages.RemoveDockedView)]
        private void OnRemoveNewDockedWindow(object parameter)
        {
            BioViewModel vm = (BioViewModel) parameter;
            DockedViews.Remove(vm);
            if (SelectedView == vm)
                SelectedView = DockedViews.Count > 0 ? DockedViews[0] : null;
        }

        private void OnViewClosed()
        {
            foreach (var item in Categories)
                item.Dispose();
        }
    }
}